package com.iwuke.dance.wallet.e_coin;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iwuke.dance.R;
import com.iwuke.dance.activity.BaseActivity;
import com.iwuke.dance.gadget_view.DefaultView;
import com.iwuke.dance.gadget_view.RefreshFooter;
import com.iwuke.dance.gadget_view.StickyHeaderTouchListener;
import com.iwuke.dance.gadget_view.TitleBarView;
import com.iwuke.dance.http_request.PathUrl;
import com.iwuke.dance.util.ClickableUtil;
import com.iwuke.dance.util.LogUtil;
import com.iwuke.dance.util.SharedPreferencesUtil;
import com.iwuke.dance.util.Util;
import com.iwuke.dance.util.merchants_connect.NetworkEvent;
import com.iwuke.dance.wallet.bean.ListETransactionRecordBean;
import com.iwuke.dance.wallet.e_coin.adapter.ECoinDetailsAdapter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * @author: 魏从响
 * @date: 2025/9/18
 * e币明细
 */
public class ECoinDetailsActivity extends BaseActivity implements View.OnClickListener {

    private TitleBarView title_bar;
    private RefreshLayout refreshLayout;
    private RecyclerView recycler_view;
    private ECoinDetailsAdapter detailsAdapter;
    private List<ListETransactionRecordBean> lists = new ArrayList<>();
    private RelativeLayout rlt_left_bt;
    private String txnType; //1 收入，2 支出;
    private TextView tv_type;
    private int pageNum=1;
    private DefaultView default_view;
    private EditText et_search;
    private ImageView img_search;
    private String findData;
    private RefreshFooter refresh_footer;
    private LinearLayout llt_e_coin;
    private View v_line;

    /**
     * @description 网络实时监听
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(NetworkEvent networkEvent){
        BaseActivity.setConnect(ECoinDetailsActivity.this,networkEvent,title_bar);

    }


    @Override
    protected int getView() {
        return R.layout.activity_e_coin_details;
    }

    @Override
    protected void init(View mView) {

        title_bar = findViewById(R.id.title_bar);
        llt_e_coin = findViewById(R.id.llt_e_coin);
        v_line = findViewById(R.id.v_line);

        rlt_left_bt = findViewById(R.id.rlt_left_bt);
        //搜索内容
        et_search = findViewById(R.id.et_search);
        //搜索按钮
        img_search = findViewById(R.id.img_search);
        //全部明细
        tv_type = findViewById(R.id.tv_type);
        refreshLayout = (RefreshLayout)findViewById(R.id.refresh_layout);
        recycler_view = findViewById(R.id.recycler_view);
        //底部加载
        refresh_footer = findViewById(R.id.refresh_footer);
        //默认视图
        default_view = findViewById(R.id.default_view);


        title_bar.setLeftOnClick(this);
        title_bar.setTitleBackgroundColor(R.color.color_ef);
        title_bar.setTitleText("E币明细");
        rlt_left_bt.setOnClickListener(this);
        //搜索按钮
        img_search.setOnClickListener(this);

    }

    @Override
    protected void initData() {

        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(ECoinDetailsActivity.this);
        recycler_view.setLayoutManager(layoutManager);

        // 初始化适配器
        detailsAdapter = new ECoinDetailsAdapter(ECoinDetailsActivity.this, R.layout.adapter_e_coin_details, lists);
        recycler_view.setAdapter(detailsAdapter);

        // 添加粘性头部装饰器
        StickyHeaderDecoration decoration = new StickyHeaderDecoration(detailsAdapter);
        recycler_view.addItemDecoration(decoration);

        new Handler(Looper.myLooper()).postDelayed(()-> {
            int height1 = title_bar.getHeight();
            int height2 = llt_e_coin.getHeight();
            int height3 = v_line.getHeight();
            int height = height1 + height2 + height3;

            // 添加触摸事件监听器
            recycler_view.addOnItemTouchListener(
                    new StickyHeaderTouchListener(ECoinDetailsActivity.this, recycler_view, decoration,height));
        },100);



        pageNum=1;
        requestData(true);

        // 设置刷新头部和底部
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));

        refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageNum=1;
            requestData(true);
        });


        // 上拉加载更多监听
        recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    Log.d("++++++++++","已经滚动到底部1");
                }

                View lastChildView = recyclerView.getLayoutManager().getChildAt(
                        recyclerView.getLayoutManager().getChildCount() - 1);

                if (lastChildView != null) {
                    int lastChildBottom = lastChildView.getBottom();
                    int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                    int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);
                    int itemCount = recyclerView.getLayoutManager().getItemCount();

                    if (lastChildBottom == recyclerBottom && lastPosition == itemCount - 1) {
                        // 精确判断已经滚动到底部
                        Log.d("++++++++++", "精确判断已经滚动到底部3");
                        refresh_footer.loading();
                        refresh_footer.setVisibility(View.VISIBLE);
                        pageNum++;
                        requestData(false);
                    }
                }

            }
        });



//        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
//        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
//        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                pageNum=1;
//                getETransactionRecord();
//            }
//        });
//        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(RefreshLayout refreshlayout) {
//                pageNum++;
//                getETransactionRecord();
//            }
//        });
//
//        pageNum=1;
//        getETransactionRecord();

    }

    private List<ListETransactionRecordBean> getLists = new ArrayList<>();
    /**
     * @description 请求数据列表
     * @param
     * @return
     * @author 魏从响
     * @time 2025/10/8 17:07
     */
    private void requestData(boolean isRefresh) {
        Map<String, String> map = new HashMap<>();
        map.put("walletId",SharedPreferencesUtil.getInstance().getWalletId());//钱包id
        map.put("page",String.valueOf(pageNum));
        if (!TextUtils.isEmpty(txnType)){
            map.put("txnType",txnType);
        }
        if (!TextUtils.isEmpty(findData)){
            map.put("findData",findData);
        }
        map.put("size",String.valueOf(20));

        PathUrl.eTransactionRecord(map, new PathUrl.DataCallBackList<ListETransactionRecordBean>() {

            @Override
            public void onSucessList(List<ListETransactionRecordBean> list) {
                //加载失败页面
                Util.setRefreshlayout(refreshLayout);//下来加载 上拉刷新 没有更多数据了
                //默认视图
                default_view.setVisibility(View.GONE);
                if (pageNum==1&&lists.size()>0){
                    getLists.clear();
                }
                List<ListETransactionRecordBean> item = new ArrayList<>();

                if (null!=list&&list.size()!=0){
                    if (pageNum==1){
                        LogUtil.logD("同月份数据list加入前",new Gson().toJson(list));
                        item.addAll(list);
                        getLists.addAll(list);
                        LogUtil.logD("同月份数据list加入后",new Gson().toJson(lists));
                    }else if (list.size()==1){//只查询出一个月份中的数据
                        if (list.get(0).month.equals(getLists.get(getLists.size()-1).month)){//同月份
                            item.add(new ListETransactionRecordBean(false, list.get(0).transactions));
                            getLists.get(getLists.size()-1).transactions.addAll(list.get(0).transactions);
                        }else {//从上个月开始的，上个月数据
                            item.addAll(list);
                            getLists.addAll(list);
                        }
                    }else if (list.size()>1){//查询出两个或多个月份中的数据
                        LogUtil.logD("","查询出两个或多个月份中的数据");
                        if (list.get(0).month.equals(getLists.get(getLists.size()-1).month)){//同月份数据
                            LogUtil.logD("同月份数据","同月份数据");
                            getLists.get(getLists.size()-1).transactions.addAll(list.get(0).transactions);
                            item.add(new ListETransactionRecordBean(false, list.get(0).transactions));
                            LogUtil.logD("同月份数据list移除前",new Gson().toJson(list));
                            list.remove(0);
                            LogUtil.logD("同月份数据list移除后",new Gson().toJson(list));
                            getLists.addAll(list);
                            item.addAll(list);
                            LogUtil.logD("同月份数据",new Gson().toJson(lists));
                        }else {//从上个月开始的多个月份中的数据
                            getLists.addAll(list);
                            item.addAll(list);
                            LogUtil.logD("从上个月开始的多个月份中的数据","同月份数据");
                        }
                    }

                    if (isRefresh) {
                        // 修改前（过时）
                        //detailsAdapter.setNewData(item);
                        // 修改后（推荐）
                        detailsAdapter.setList(item); // 适用于 3.x 版本;依赖：implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4' // 请确认此处的版本号
                        //detailsAdapter.submitList(item);//（适用于 4.x及以上）
                        refreshLayout.finishRefresh();
                    } else {
                        detailsAdapter.addData(item);
                        refreshLayout.finishLoadMore();
                    }
                    refresh_footer.loadedSuccessfully();//加载成功

                }else {
                    if (pageNum==1){
                        getLists.clear();
                    }

                    if (getLists==null||getLists.size()==0){
                        default_view.setTextView("没有数据~");
                        default_view.setVisibility(View.VISIBLE);
                    }
                    if (pageNum>1){//当前页没数据，页数减一
                        LogUtil.logD("没有更多数据了","没有更多数据了");
                        pageNum--;
                        refreshLayout.setNoMoreData(true);//没有更多数据了
                        refreshLayout.finishLoadMoreWithNoMoreData();
                        refresh_footer.noMoreDataAvailable();
                    }
                }
                new Handler(Looper.myLooper()).postDelayed(()-> {
                    refresh_footer.setVisibility(View.GONE);
                },100);//隐藏尾部
            }

            @Override
            public void onFail(String errorCode) {
                refresh_footer.setVisibility(View.GONE);
                Util.setRefreshlayout(refreshLayout);//下来加载 上拉刷新 没有更多数据了
                default_view.setTextView(errorCode);
                default_view.setVisibility(View.VISIBLE);
            }
        });
    }

    private void getETransactionRecord() {

        Map<String, String> map = new HashMap<>();
        map.put("walletId",SharedPreferencesUtil.getInstance().getWalletId());//钱包id
        map.put("page",String.valueOf(pageNum));
        if (!TextUtils.isEmpty(txnType)){
            map.put("txnType",txnType);
        }
        if (!TextUtils.isEmpty(findData)){
            map.put("findData",findData);
        }
        map.put("size",String.valueOf(20));

        PathUrl.eTransactionRecord(map, new PathUrl.DataCallBackList<ListETransactionRecordBean>() {

            @Override
            public void onSucessList(List<ListETransactionRecordBean> list) {
                //加载失败页面
                Util.setRefreshlayout(refreshLayout);//下来加载 上拉刷新 没有更多数据了
                //默认视图
                default_view.setVisibility(View.GONE);
                if (pageNum==1&&lists.size()>0){
                    lists.clear();
                }

                if (null!=list&&list.size()!=0){
                    if (pageNum==1){
                        LogUtil.logD("同月份数据list加入前",new Gson().toJson(list));
                        lists.addAll(list);
                        LogUtil.logD("同月份数据list加入后",new Gson().toJson(lists));
                    }else if (list.size()==1){//只查询出一个月粉中的数据
                        if (list.get(0).month.equals(lists.get(lists.size()-1).month)){//同月份
                            lists.get(lists.size()-1).transactions.addAll(list.get(0).transactions);
                        }else {//从上个月开始的，上个月数据
                            lists.addAll(list);
                        }
                    }else if (list.size()>1){//查询出两个或多个月份中的数据
                        LogUtil.logD("","查询出两个或多个月份中的数据");
                        if (list.get(0).month.equals(lists.get(lists.size()-1).month)){//同月份数据
                            LogUtil.logD("同月份数据","同月份数据");
                            lists.get(lists.size()-1).transactions.addAll(list.get(0).transactions);
                            LogUtil.logD("同月份数据list移除前",new Gson().toJson(list));
                            list.remove(0);
                            LogUtil.logD("同月份数据list移除后",new Gson().toJson(list));
                            lists.addAll(list);
                            LogUtil.logD("同月份数据",new Gson().toJson(lists));
                        }else {//从上个月开始的多个月份中的数据
                            lists.addAll(list);
                            LogUtil.logD("从上个月开始的多个月份中的数据","同月份数据");
                        }
                    }
                    refreshLayout.setEnableLoadMore(true);//有数据上拉加载成功
                }else {
                    if (pageNum==1){
                        lists.clear();
                    }

                    if (lists==null||lists.size()==0){
                        default_view.setTextView("没有数据~");
                        default_view.setVisibility(View.VISIBLE);
                    }
                    if (pageNum>1){//当前页没数据，页数减一
                        LogUtil.logD("没有更多数据了","没有更多数据了");
                        pageNum--;
                        refreshLayout.setNoMoreData(true);//没有更多数据了
                    }
                }

                if (detailsAdapter==null) {
                    setLinearLayoutManager(ECoinDetailsActivity.this, recycler_view);
                    detailsAdapter = new ECoinDetailsAdapter(ECoinDetailsActivity.this, R.layout.adapter_e_coin_details, lists);
                    recycler_view.setAdapter(detailsAdapter);
                }else {
                    //detailsAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onFail(String errorCode) {
                Util.setRefreshlayout(refreshLayout);//下来加载 上拉刷新 没有更多数据了
                default_view.setTextView(errorCode);
                default_view.setVisibility(View.VISIBLE);
            }
        });
    }

    public void setMemberManagement(Context context) {

        //对于 PopupWindow，正确的做法是在 inflate 时传入 null，但需要确保在创建 PopupWindow 对象时明确指定宽度和高度。你的代码已经做到了这一点，这是关键。
        //因此，消除这个警告最直接有效的方法是在 inflate 方法上使用 @SuppressLint 注解，明确告知编译器你了解这个情况并有意为之：
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(context).inflate(R.layout.popup_window_e_coin, null);
        final PopupWindow popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        //新方法：使用透明的 ColorDrawable   new ColorDrawable(Color.TRANSPARENT)和new BitmapDrawable()一样
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置白色背景
        //popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        //创建带圆角的背景 首先，在 res/drawable 目录下创建一个 XML 文件（如 popup_background.xml）：
        //popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.popup_background));
        //使用 NinePatch 图片作为背景 如果你的设计需要更复杂的背景效果，可以使用 .9.png 图片：
        //popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.your_nine_patch_background));
        //设置点击弹窗外隐藏自身
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        //设置位置 在某个控件下面
//        popupWindow.showAsDropDown(tv_search,-10,10);
        //设置位置
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        RelativeLayout rlt_popup_window_bg = view.findViewById(R.id.rlt_popup_window_bg);
        LinearLayout llt_popup_window = view.findViewById(R.id.llt_popup_window);
        TextView tv_all = view.findViewById(R.id.tv_all);//全部
        TextView tv_income = view.findViewById(R.id.tv_income);//收入
        TextView tv_expenditure = view.findViewById(R.id.tv_expenditure);//支出

        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);

        if ("1".equals(txnType)){
            //收入明细
            setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.color_000,R.drawable.bg_radius6_color_d8_shape,
                    R.color.white,R.drawable.bg_radius6_color_000_shape,R.color.color_000,R.drawable.bg_radius6_color_d8_shape);
        }else if ("2".equals(txnType)){
            //支出明细
            setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.color_000,R.drawable.bg_radius6_color_d8_shape,
                    R.color.color_000,R.drawable.bg_radius6_color_d8_shape,R.color.white,R.drawable.bg_radius6_color_000_shape);
        }else {
            //全部明细
            setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.white,R.drawable.bg_radius6_color_000_shape,
                    R.color.color_000,R.drawable.bg_radius6_color_d8_shape,R.color.color_000,R.drawable.bg_radius6_color_d8_shape);
        }

        //全部
        final String[] type = {""};
        tv_all.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.white,R.drawable.bg_radius6_color_000_shape,
                        R.color.color_000,R.drawable.bg_radius6_color_d8_shape,R.color.color_000,R.drawable.bg_radius6_color_d8_shape);
                type[0] = "";

            }
        });

        //收入
        tv_income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.color_000,R.drawable.bg_radius6_color_d8_shape,
                        R.color.white,R.drawable.bg_radius6_color_000_shape,R.color.color_000,R.drawable.bg_radius6_color_d8_shape);
                type[0] = "1";

            }
        });

        //支出
        tv_expenditure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTextViewType(context,tv_all,tv_income,tv_expenditure,R.color.color_000,R.drawable.bg_radius6_color_d8_shape,
                        R.color.color_000,R.drawable.bg_radius6_color_d8_shape,R.color.white,R.drawable.bg_radius6_color_000_shape);

                type[0] = "2";
            }
        });

        rlt_popup_window_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        llt_popup_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txnType = type[0];
                if ("1".equals(type[0])){
                    tv_type.setText("收入明细");
                }else if ("2".equals(type[0])){
                    tv_type.setText("支出明细");
                }else {
                    tv_type.setText("全部明细");
                }
//                pageNum=1;
//                getETransactionRecord();
                pageNum=1;
                requestData(true);
                popupWindow.dismiss();
            }
        });
    }

    private void setTextViewType(Context context,TextView tv_all, TextView tv_income, TextView tv_expenditure,
                                 int color1, int bg1, int color2, int bg2, int color3, int bg3) {
        tv_all.setTextColor(context.getResources().getColor(color1,null));
        tv_all.setBackgroundResource(bg1);
        tv_income.setTextColor(context.getResources().getColor(color2,null));
        tv_income.setBackgroundResource(bg2);
        tv_expenditure.setTextColor(context.getResources().getColor(color3,null));
        tv_expenditure.setBackgroundResource(bg3);
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.img_left){
            finish();
        }else if (v.getId()==R.id.rlt_left_bt){
            setMemberManagement(ECoinDetailsActivity.this);
        }else if (v.getId()==R.id.img_search){//搜索按钮
            new ClickableUtil().isClickable(img_search);//设置点击间隔
            findData = et_search.getText().toString();
//            pageNum=1;
//            getETransactionRecord();
            pageNum=1;
            requestData(true);
        }
    }
}
